import axios from 'axios'
import qs from 'qs'
import { Message } from "element-ui";


const Axios = axios.create({
  baseURL: "http://127.0.0.1:10000/sys", // 因为我本地做了反向代理
  timeout: 3000,
  responseType: "json",
  withCredentials: false, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  }
});
Axios.interceptors.request.use(
    config => {
        if(
            config.method==='post'||
            config.method==='put'||
            config.method==='delete'
        ){
            if(config.data){
                config.data = qs.stringify(config.data);
            }
        }
        if (localStorage.token) {
            config.headers.Authorization = localStorage.token;
        }
        return config;
    },
    error => {
        Message({
            showColse: true,
            message: '请求错误',
            type: 'error'
        });
        return Promise.reject(error);
    }
)

Axios.interceptors.response.use(
    response => {
        if(response.data.code!=0){
            Message({
                showColse: true,
                message: response.data.errMsg,
                type: 'error'
            })
            return Promise.reject(response);
        }
        return response;
    },
    error => {
        Message({
                showColse: true,
                message: '返回错误',
                type: 'error'
            })
        return Promise.reject(error);
    }
);

function fetch(url,params){
        return new Promise((resolve,reject)=>{
            Axios.post(url,params)
            .then(response=>{
                resolve(response.data);
            },err=>{
                reject(err);
            })
            .catch(error=>{
                reject(error)
            })
        });
    }

export default {
    fetch
}